package com.wei.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class ErrorException extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.DEBUG_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        try{
            RequestContext currentContext = RequestContext.getCurrentContext();
            ZuulException exception =  (ZuulException)currentContext.getThrowable();
            System.out.println("异常拦截：" + exception.getMessage());
            HttpServletResponse response = currentContext.getResponse();
            response.setContentType("text/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(exception.nStatusCode);

            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.print("{code:100}");
            }
            catch (IOException ex){
                ex.printStackTrace();
            }finally {
                if(writer!=null){
                    writer.flush();
                    writer.close();
                }
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
        }

        return null;
    }
}
